package com.sun.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.sun.mapper.EmployeeMapper;
import com.sun.pojo.Employee;
import com.sun.pojo.User;
import com.sun.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

@Controller
public class HelloController {
    /**
     * @return
     * @RequestParm:获取请求参数 如果带了参数 请求时必须带参数
     * @RequestParam("userName") String userName 相当于 request.getParameter("userName")
     * value:指定获取参数的key
     * required:true必须带参数,false不必须带参数
     * defaultValue:如果没带参数,指定默认的参数值
     * @PathVariable:获取路径上的值
     * @RequestHeader:
     * @RequestHeader("User-Agent") String userAgent 相当于 Request.getHeader("User-Agent")
     * 如果请求头中没有这个值会报500错
     * @CookieValue
     */
    @RequestMapping("/handle02")
    @ResponseBody
    public String handle02(@RequestParam(value = "userName", defaultValue = "你忘记带参数了,孩子") String userName,
                           @RequestHeader("User-Agent") String userAgent,
                           @CookieValue(value = "JSESSIONID", defaultValue = "你忘记带参数了,孩子", required = false) String cooke) {
        System.out.println(userName);
        System.out.println(userAgent);
        System.out.println(cooke);
        return "success";
    }

    @RequestMapping("/handle03")
    @ResponseBody
    public User handle03(@Valid User user, BindingResult result) {
        System.out.println(result);
        System.out.println("============================");
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError allError : allErrors) {
                System.out.println(allError.getCode());
                System.out.println(allError.getDefaultMessage());
            }
        }
        System.out.println(user);
        return user;
    }

    @Autowired
    EmployeeMapper employeeMapper;

    @RequestMapping("/handle04")
    @ResponseBody
    public Employee handle04() {
        Employee allEmpl = employeeMapper.getAllEmpl();

        System.out.println(allEmpl);
        return null;
    }

    @RequestMapping("/handle05")
    @ResponseBody
    public Employee handle05(String name) {
        Employee allEmpl = employeeMapper.getEmplByName(name);

        System.out.println(allEmpl);
        return null;
    }




    @RequestMapping("/handle06")
    @ResponseBody
    @Transactional
    public int handle06(String name, String id) {
        int i = employeeMapper.updateEmplName(name, id);
        try {
            int k = 1 / 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        int j = employeeMapper.updateEmplName("尼玛", "2");

        return 1;

    }

    @Autowired
    private TestService testService;

    @RequestMapping("/testSer")
    @ResponseBody
    public String test() {
        System.out.println("con请求开始");
        ThreadUtil.sleep(3000);
//        testService.test();
        System.out.println("con请求结束");
        return "succ";
    }

    @RequestMapping("/getSessionId")
    @ResponseBody
    public String getSessionId(HttpServletRequest request, HttpServletResponse response, String id) {
        HttpSession session = request.getSession();
        session.setAttribute("getId", id);
        System.out.println("id = >" + session.getId());
        Cookie cookie = new Cookie("sessionid", session.getId());
        cookie.setMaxAge(120);
        response.addCookie(cookie);
        return session.getId();
    }

    @RequestMapping("/getId")
    @ResponseBody
    public String getId(HttpServletRequest request, String id) {
        HttpSession session = request.getSession();
        System.out.println("id = >" + session.getId());
        return (String) session.getAttribute("getId");
    }

    @PostMapping("/testJdkHttp")
    @ResponseBody
    public Map testJdkHttp(@RequestBody Map map) {
        System.out.println("获得的值================");
        System.out.println(map);
        return map;
    }

    public static void main(String[] args) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        String jsonData = "{\"body\":{\"voucher_detail\":[{\"internalDepCode\":\"100001\"," +
                "\"payeeAcctName\":\"孙成利\",\"agencyId\":\"1524642795657236480\",\"agencyCode\":\"904201\"," +
                "\"payBusTypeName\":\"普通业务\",\"depBgtEcoName\":\"商品和服务支出\",\"setModeName\":\"电子同城转账\"," +
                "\"payAcctBankName\":\"中国银行\",\"internalDepId\":\"1524654951181127681\",\"internalDepName\":\"财务部\"," +
                "\"payAcctNo\":\"6222025567367254271\",\"bgtId\":\"ced9f67fe9124b3b836a8e7215d77e65\"," +
                "\"govBgtEcoCode\":\"50502\",\"trackingId\":\"1546742628094185472\",\"useDes\":\"其他公安支出\"," +
                "\"payAcctName\":\"账户003\",\"batchNo\":\"1\",\"setModeCode\":\"11\",\"trackingCode\":\"ZF20220712141\"," +
                "\"agencyName\":\"FRMAIN单位\",\"payeeAcctNo\":\"6222023234393778132\",\"payTypeName\":\"授权支付\"," +
                "\"payAppAmt\":9,\"payTypeCode\":\"12\",\"payBusTypeCode\":\"1\",\"fundTraobjTypeCode\":\"21\"," +
                "\"depBgtEcoCode\":\"302\",\"payTypeId\":\"1401838317074022102\",\"payeeAcctBankName\":\"中国银行\"," +
                "\"govBgtEcoName\":\"商品和服务支出\",\"fundTraobjTypName\":\"与部门内下级单位\"}],\"agency_code\":\"904201\"," +
                "\"mof_div_code\":\"410000000\",\"page_no\":1,\"fiscal_year\":\"2022\",\"track_app_id\":\"902\"," +
                "\"page_size\":500}}";
        try {
            URL url = new URL("http://127.0.0.1:80/springMvc/testJdkHttp");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(120000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");


            os = connection.getOutputStream();
            if (jsonData != null && jsonData.length() > 0) {
                os.write(jsonData.getBytes("UTF-8"));
                os.flush();
            }

            int i;
            StringBuffer sbf;
            String line = "";
            if (connection.getResponseCode() != 200) {
                if (null != connection.getErrorStream()) {
                    is = connection.getErrorStream();
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    sbf = new StringBuffer();

                    for (i = 0; (line = br.readLine()) != null; ++i) {
                        if (i > 0) {
                            sbf.append("\r\n");
                        }

                        sbf.append(line);
                    }

                    result = sbf.toString();
                    throw new Exception(connection.getResponseCode() + result);
                }

                throw new Exception(String.valueOf(connection.getResponseCode()));
            }

            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            sbf = new StringBuffer();
            line = null;

            for (i = 0; (line = br.readLine()) != null; ++i) {
                if (i > 0) {
                    sbf.append("\r\n");
                }

                sbf.append(line);
            }

            result = sbf.toString();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception var23) {
                }
            }

            if (br != null) {
                try {
                    br.close();
                } catch (Exception var22) {
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (Exception var21) {
                }
            }

            if (null != connection) {
                connection.disconnect();
            }

        }
    }
}
